import axios from 'axios'
import router from '@/router/routers'
import { Notification, MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, setToken, removeToken } from '@/utils/auth'
import Settings from '@/settings'

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: Settings.timeout, // 请求超时时间
  // withCredentials: true,         // 表示跨域请求时是否需要使用凭证
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  },
  isRetryRequest: false
})

let requestConfig = null // 存储请求失败

// request interceptor
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['token'] = getToken() // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    }
    // config.headers['Content-Type'] = 'application/json'

    if (config.params && config.params.filters) {
      config.params.filters = encodeURI(JSON.stringify(config.params.filters))
    }
    requestConfig = config
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// respone interceptor
service.interceptors.response.use(
  response => {
    const code = response.status
    if (code < 200 || code > 300) {
      Notification.error({
        title: response.message
      })
      return Promise.reject('error')
    } else {
      if (response.data && response.data.code === 401) { // 401, token失效
        Message.error('401,登录超时，请重新登录')
        refreshTokenRequest(requestConfig)// 刷新token,重新请求
      }
      return response.data
    }
  },
  error => {
    let code = 0
    try {
      code = error.response.status
    } catch (e) {
      if (error.toString().indexOf('Error: timeout') !== -1) {
        Notification.error({
          title: '网络请求超时',
          duration: 2500
        })
        return Promise.reject(error)
      }
      if (error.toString().indexOf('Error: Network Error') !== -1) {
        Notification.error({
          title: '网络请求错误',
          duration: 2500
        })
        return Promise.reject(error)
      }
    }

    if (code === 401) {
      removeToken()
      MessageBox.alert('登录状态已过期，请重新登录', '信息提示', {
        callback: () => {
          store.dispatch('logOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        }
      })
    // } else if (code === 401) {
    //   router.push({ path: '/401' })
    } else if (code === 404) {
      // router.push({ path: '/404' })
      const errorMsg = error.response.data.message
      if (errorMsg !== undefined) {
        Notification.error({
          title: '404：' + errorMsg,
          duration: 2500
        })
      }
    } else if (code === 403) {
      // router.push({ path: '/401' })
      const errorMsg = error.response.data.message
      if (errorMsg !== undefined) {
        Notification.error({
          title: '403：' + errorMsg,
          duration: 2500
        })
      }
    } else {
      const errorMsg = error.response.data.message
      if (errorMsg !== undefined) {
        Notification.error({
          title: errorMsg,
          duration: 2500
        })
      }
    }
    return Promise.reject(error)
  }
)

// 刷新token的请求方法
function getRefreshToken() {
  const params = {
    token: store.getters.token
  }
  return axios.post(process.env.BASE_API + '/sys/freshToken', params)
}
// 刷新token,重新请求
function refreshTokenRequest(config) {
  if (!config.isRetryRequest) {
    // 刷新token
    return getRefreshToken().then(function(response) {
      if (response.code === 0 && response.data.token) {
        const data = response.data
        // 修改flag
        config.isRetryRequest = true
        // 修改原请求的token
        setToken(data.token)
        store.commit('SET_TOKEN', data.token)
        config.headers['token'] = data.token
        /* 这边不需要baseURL是因为会重新请求url
        *url中已经包含baseURL的部分了
        *如果不修改成空字符串，会变成'api/api/xxxx'的情况*/
        config.baseURL = ''
        // 重新请求
        return axios(config)
      } else {
        removeToken()
        router.push({
          name: 'login',
          query: { redirect: router.currentRoute.fullPath }
        }, () => {
          location.reload() // 刷新页面, 清空整站临时存储数据
        })
      }
    }).catch(error => {
      removeToken()
      router.push({
        name: 'login',
        query: { redirect: router.currentRoute.fullPath }
      }, () => {
        location.reload() // 刷新页面, 清空整站临时存储数据
      })
      console(error)
    })
  }
}

export default service
